//
//  MyViewController.m
//  Organic
//
//  Created by sunx on 15/3/22.
//  Copyright (c) 2015年 Mike Amaral. All rights reserved.
//
#define SERVE @"http://samoyun.com/controller/blogController.php"

#import "NSURLSession+KKAddition.h"
#import "MyViewController.h"
#import "EditViewController.h"
#import "TextFieldCell.h"
#import "SVProgressHUD.h"
#import "AxisCell.h"
#import "GDataXMLNode.h"

@interface MyViewController ()
@property(nonatomic,strong) NSArray *axises;
@property(nonatomic,strong) NSString *username;
@end

@implementation MyViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    self.view.backgroundColor = [UIColor colorWithRed:92.0/255.0 green:92.0/255.0 blue:92.0/255 alpha:0.9];
    NSUserDefaults *userDefault = [NSUserDefaults standardUserDefaults];
    self.username = [userDefault valueForKey:@"username"];
    self.title = @"AXIS";
    
    UIBarButtonItem *barButton = [[UIBarButtonItem alloc] initWithBarButtonSystemItem:UIBarButtonSystemItemAdd target:self action:@selector(jumpToEdit)];
    self.navigationItem.rightBarButtonItem = barButton;
}
-(void)viewWillAppear:(BOOL)animated {
    [SVProgressHUD show];
    [NSURLSession GET:SERVE pararms:@{@"user":self.username,@"type":@"axis"} completed:^(NSData *data) {
        NSError *error;
        GDataXMLDocument *document = [[GDataXMLDocument alloc] initWithData:data options:0 error:&error];
        NSArray *arr = [[[document rootElement] children][1] children];
        self.axises = arr;
        
        [self performSelectorOnMainThread:@selector(updateTable) withObject:self waitUntilDone:YES];
        
    } failed:^(NSError *error) {
        if(!error) {
            NSLog(@"%@",error);
        }
    }];
}
- (void)jumpToEdit {
    EditViewController *viewController = [[EditViewController alloc] initWithType:@"axis"];
    [self.navigationController pushViewController:viewController animated:YES];
}

- (void)updateTable {
    NSMutableArray *cells = [NSMutableArray new];
    
    for(int i = (int)[self.axises count]-1; i >=0 ; i--) {
        NSString *body = [[self.axises[i] children][0] stringValue];
        NSString *date = [[self.axises[i] children][1] stringValue];
        NSString *image = [[self.axises[i] children][2] stringValue];
        
        AxisCell *cell = [[AxisCell alloc] initWithImage:image andBody:body andDate:date];
        [cells addObject:cell];
    }
    OrganicSection *sec = [OrganicSection sectionWithCells:cells];
    
    self.sections = @[sec];
    
    [self.tableView reloadData];
    
    [SVProgressHUD dismiss];
}
- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
}

@end
